package com.she.olympic;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import com.adon.ar.test.ARExampleActivity;

import ken.app.helper.Helper;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class SplashScreenActivity extends Activity {
	protected boolean _active = true;
	protected int _splashTime  = 2000;
	protected Timer timer;
	protected boolean internetConnection = false;
	private ConnectivityManager mConnectivityManager = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.splash);
						
		//判對是否第一次開啟
		SharedPreferences settings = SplashScreenActivity.this.getSharedPreferences("AR", Activity.MODE_PRIVATE); 
		boolean isfirst = settings.getBoolean("first", true);
		
		mConnectivityManager = (ConnectivityManager) SplashScreenActivity.this.getSystemService(SplashScreenActivity.this.CONNECTIVITY_SERVICE);
		
		if (isfirst) {
			String[] title = {"不允許" ,"好"};
			Helper.ShowMessage(SplashScreenActivity.this, "", "“中華加油照集令”要傳送推播通知通知可包含提示、聲音和圖像標記。可在”設定”裡進行設定。", 2, title, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					/*不開啟推播繼續後續動作*/
					if (isNetworkAvailable()) {
						internetConnection = true; 
						timer = new Timer(true);
						timer.schedule(task, 0, 500);
					}
					else{
						timer = new Timer(true);
						timer.schedule(task, 0, 500);
						
						String[] title2 = {"設定" ,"好"};
						Helper.ShowMessage(SplashScreenActivity.this, "網路連線失敗", "請確認網路連線是否正常", 2, title2, 
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO 網路連線失敗設定
								startActivity(new Intent(Settings.ACTION_SETTINGS));
							}
						} 
						,null 
						,new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
//								android.os.Process.killProcess(android.os.Process.myPid());
							}
						});
					}
				}
			} 
			,null 
			,new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
		        	/*開啟推播*/
		            Olympic olympic = (Olympic) getApplicationContext();
		            olympic.enablePush(true);
		            
					if (isNetworkAvailable()) {
						internetConnection = true; 
						timer = new Timer(true);
						timer.schedule(task, 0, 500);
					}
					else{
						timer = new Timer(true);
						timer.schedule(task, 0, 500);
						
						String[] title2 = {"設定" ,"好"};
						Helper.ShowMessage(SplashScreenActivity.this, "網路連線失敗", "請確認網路連線是否正常", 2, title2, 
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO 網路連線失敗設定
								startActivity(new Intent(Settings.ACTION_SETTINGS));
							}
						} 
						,null 
						,new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
//								android.os.Process.killProcess(android.os.Process.myPid());
							}
						});
					}
				}
			});
		}else{
			
			if (isNetworkAvailable()) {
				internetConnection = true; 
				timer = new Timer(true);
				timer.schedule(task, 0, 500);
			}
			else{
				timer = new Timer(true);
				timer.schedule(task, 0, 500);
				
				String[] title2 = {"設定" ,"好"};
				Helper.ShowMessage(this, "網路連線失敗", "請確認網路連線是否正常", 2, title2, 
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO 網路連線失敗設定
						startActivity(new Intent(Settings.ACTION_SETTINGS));
					}
				} 
				,null 
				,new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
//						android.os.Process.killProcess(android.os.Process.myPid());
					}
				});
			}
		}
				
		settings.edit().putBoolean("first", false).commit();//記錄開啟非第一次
		//建立資料夾
		File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/.olympic/");
		if(!dir.exists()){
			dir.mkdirs();
		}
	}

	private final Handler timerHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				RelativeLayout relativeLayout = (RelativeLayout) LayoutInflater.from(SplashScreenActivity.this).inflate(R.layout.splash, null);
				BitmapDrawable drawable = (BitmapDrawable) relativeLayout.getBackground();
				relativeLayout.getBackground().setCallback(null);
				if (null != drawable && !drawable.getBitmap().isRecycled()){
					drawable.getBitmap().recycle();
					drawable = null;
			    }
				relativeLayout = null;
				timer.cancel();
				SplashScreenActivity.this.finish();
				overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
				Intent it = new Intent();
				it.setClass(SplashScreenActivity.this, MyAppActivity.class);
				startActivity(it);
				overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
				System.gc();
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	
//	// 檢查網路連線是否正常之副程式
//    public boolean checkInternetConnection(String strURL, String strEncoding) {
//        // 此副程式之特性是僅用於連線測試, 不是開啟網頁,
//        // 因此, Google Analytics 並不會納入分析報表中, 但 Google App Engine 會有記錄.
//      
//        // 最多延時 n 秒若無回應則表示無法連線
//        int intTimeout = 5000; // 1000 = 1 秒
//        try {
//            HttpURLConnection urlConnection= null;
//            URL url = new URL(strURL);
//            urlConnection=(HttpURLConnection)url.openConnection();
//            urlConnection.setRequestMethod("GET");
//            urlConnection.setDoOutput(true);
//            urlConnection.setDoInput(true);
//            urlConnection.setRequestProperty("User-Agent",this.getPackageName()); // 自定訊息-程式名
//            urlConnection.setRequestProperty("Content-type","text/html; charset="+strEncoding);
//            urlConnection.setConnectTimeout(intTimeout);
//            urlConnection.connect();
//            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { // Code 回應為 200 表連線正常
//                return true; // 函式回傳 true 值, 因連線成功.
//            } else {
//                return false; // 函式回傳 false 值, 因連線失敗.
//            }          
//        } catch (Exception e) {
//          e.printStackTrace();
//          return false; // 函式回傳 false 值, 因不明原因的執行期錯誤.
//        }
//    }
	
	public boolean isNetworkAvailable() {
		boolean isAvailable = true;
//	   	if(mConnectivityManager != null) {
//	   		NetworkInfo[] info = mConnectivityManager.getAllNetworkInfo();
//	   		if(info != null) {
//	   			for(int i = 0; i < info.length; i++) {
//	   				if(info[i].getState() == NetworkInfo.State.CONNECTED) {
//	   					isAvailable = true;
//	   					break;
//	   				}
//	   			}
//	   		}
//	   	}
	   	return isAvailable;
	}

	@Override
	public void onBackPressed() {
		timer.cancel();
		android.os.Process.killProcess(android.os.Process.myPid());
		super.onBackPressed();
	}
	
	private final TimerTask task = new TimerTask() {
		@Override
		public void run() {
			if (_splashTime == 0 && internetConnection) {
				Message message = new Message();
				message.what = 0;
				timerHandler.sendMessage(message);
				timer.cancel();
				this.cancel();
			}else if(internetConnection && _splashTime != 0){
				_splashTime -= 500 ;
			}else if (!internetConnection){
				if (isNetworkAvailable()) {
					internetConnection = true;
				}
			}
			
		}
	};

//	@Override
//	public boolean onTouchEvent(MotionEvent event) {
//		if (event.getAction() == MotionEvent.ACTION_DOWN) {
//			_active = false;
//		}
//		return true;
//	}
}